package com.yuwj.chinaa.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.yuwj.chinaa.R;
import com.yuwj.chinaa.adapter.MyComputeCodeAdapter;
import com.yuwj.chinaa.base.BaseActivity;
import com.yuwj.chinaa.entity.EntityComputeCode;
import com.yuwj.chinaa.entity.EntityMyComputeCode;
import com.yuwj.chinaa.presenter.IPresenter;
import com.yuwj.chinaa.presenter.presenterImpl.PresenterImpl;
import com.yuwj.chinaa.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 我的算码
 */
public class MyComputeCodeActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.v_bg1)
    View vBg1;
    @BindView(R.id.v_bg2)
    View vBg2;
    @BindView(R.id.tv_profit)
    TextView tvProfit;
    @BindView(R.id.tv_miner_number)
    TextView tvMinerNumber;
    @BindView(R.id.tv_curr_efficiency)
    TextView tvCurrEfficiency;
    @BindView(R.id.tv_total_profit)
    TextView tvTotalProfit;

    AlertDialog dialogWithPayPasswordInput;//支付密码输入框
    AlertDialog dialogWithReturnPayPasswordInput;//退还支付密码输入框
    double currentMinerDeposit;//当前选中算码的押金数量
    IPresenter presenter;
    List<EntityComputeCode> entityComputeCodeList;
    MyComputeCodeAdapter myComputeCodeAdapter;
    boolean isUpActivityNeedRefresh;//上个页面是否需要刷新,在交了押金和退还押金后需要更新上个页面
    @BindView(R.id.rl_miner_number)
    RelativeLayout rlMinerNumber;

    public static Intent createIntent(Context context) {
        Intent intent = new Intent(context, MyComputeCodeActivity.class);
        return intent;
    }

    @Override
    public int setCustomContentViewResourceId() {
        return R.layout.activity_asset_my_compute_code;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                if (isUpActivityNeedRefresh) {
                    setResult(RESULT_OK);
                    finish();
                } else {
                    onBackPressed();
                }
                break;
        }
        return true;
    }

    @Override
    public void initParam() {
        presenter = new PresenterImpl(this);
        entityComputeCodeList = new ArrayList<>();
        myComputeCodeAdapter = new MyComputeCodeAdapter(context, entityComputeCodeList);
        myComputeCodeAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_deposit:
                        final EntityComputeCode entityMiner = myComputeCodeAdapter.getItem(position);
                        currentMinerDeposit = entityMiner.getDeposit();
                        if (entityMiner.isNeedDeposit()) {//支付押金
                            if (dialogWithPayPasswordInput == null) {
                                AlertDialog.Builder builderWithPay = new AlertDialog.Builder(context);
                                LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.content_input_pay_password, null);
                                final EditText etPayPassword = (EditText) layout.findViewById(R.id.et_pay_password);
                                LinearLayout llDismiss = (LinearLayout) layout.findViewById(R.id.ll_dismiss);
                                final TextView tvTitle = (TextView) layout.findViewById(R.id.tv_title);
                                tvTitle.setText("支付算码押金" + currentMinerDeposit + "GTE");
                                TextView tvNextStep = (TextView) layout.findViewById(R.id.tv_next);
                                View.OnClickListener onClickListener = new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        switch (view.getId()) {
                                            case R.id.ll_dismiss:
                                                dialogWithPayPasswordInput.dismiss();
                                                dialogWithPayPasswordInput = null;
                                                break;
                                            case R.id.tv_next:
                                                String passwrod = etPayPassword.getText().toString();
                                                if (TextUtils.isEmpty(passwrod)) {
                                                    ToastUtil.getInstance().shortLength(context, "请输入支付密码");
                                                    return;
                                                }
                                                JSONObject param = new JSONObject();
                                                try {
                                                    param.put("minerId", entityMiner.getId());
                                                    param.put("deposit", currentMinerDeposit + "");
                                                    param.put("payPassword", passwrod);

                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                                presenter.minerPayDeposit(param.toString());
                                                etPayPassword.setText("");//发送请求后,清空输入的密码
                                                dialogWithPayPasswordInput.dismiss();
                                                dialogWithPayPasswordInput = null;
                                                break;
                                        }
                                    }
                                };
                                llDismiss.setOnClickListener(onClickListener);
                                tvNextStep.setOnClickListener(onClickListener);
                                dialogWithPayPasswordInput = builderWithPay.setView(layout).create();
                            }
                            dialogWithPayPasswordInput.show();
                        } else {//退还押金
                            if (dialogWithReturnPayPasswordInput == null) {
                                AlertDialog.Builder builderWithPay = new AlertDialog.Builder(context);
                                LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.content_input_pay_password, null);
                                final EditText etPayPassword = (EditText) layout.findViewById(R.id.et_pay_password);
                                LinearLayout llDismiss = (LinearLayout) layout.findViewById(R.id.ll_dismiss);
                                final TextView tvTitle = (TextView) layout.findViewById(R.id.tv_title);
                                tvTitle.setText("退还算码押金" + currentMinerDeposit + "GTE");
                                TextView tvNextStep = (TextView) layout.findViewById(R.id.tv_next);
                                View.OnClickListener onClickListener = new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        switch (view.getId()) {
                                            case R.id.ll_dismiss:
                                                dialogWithReturnPayPasswordInput.dismiss();
                                                dialogWithReturnPayPasswordInput = null;
                                                break;
                                            case R.id.tv_next:
                                                String passwrod = etPayPassword.getText().toString();
                                                if (TextUtils.isEmpty(passwrod)) {
                                                    ToastUtil.getInstance().shortLength(context, "请输入支付密码");
                                                    return;
                                                }
                                                JSONObject param = new JSONObject();
                                                try {
                                                    param.put("minerId", entityMiner.getId());
                                                    param.put("payPassword", passwrod);

                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                                presenter.minerReturnDeposit(param.toString());
                                                etPayPassword.setText("");//发送请求后,清空输入的密码
                                                dialogWithReturnPayPasswordInput.dismiss();
                                                dialogWithReturnPayPasswordInput = null;
                                                break;
                                        }
                                    }
                                };
                                llDismiss.setOnClickListener(onClickListener);
                                tvNextStep.setOnClickListener(onClickListener);
                                dialogWithReturnPayPasswordInput = builderWithPay.setView(layout).create();
                            }
                            dialogWithReturnPayPasswordInput.show();
                        }

                        break;
                }
            }
        });
    }

    @Override
    public void initView() {
        initActionBar(toolbar, tvTitle, "我的算码");
        rvList.setAdapter(myComputeCodeAdapter);
        rvList.setLayoutManager(new LinearLayoutManager(context));
    }

    @Override
    public void initOperator() {
        JSONObject param = new JSONObject();
        presenter.queryUserMinerList(param.toString());
    }

    @Override
    public void onQueryUserMinerListSuccess(EntityMyComputeCode entityMyComputeCode) {
        super.onQueryUserMinerListSuccess(entityMyComputeCode);
        entityComputeCodeList.clear();
        entityComputeCodeList.addAll(entityMyComputeCode.getUserGteMinerList());
        myComputeCodeAdapter.notifyDataSetChanged();
        tvProfit.setText("" + entityMyComputeCode.getProfit() + "");
        tvMinerNumber.setText("总算码数量:" + entityMyComputeCode.getMinerNumber() + "台");
        tvCurrEfficiency.setText("当前算力:" + entityMyComputeCode.getCurrEfficiency() + "GTE/S");
        tvTotalProfit.setText("累计获得:" + entityMyComputeCode.getTotalProfit() + "GTE");
    }

    @Override
    public void onQueryUserMinerListFail(Exception e) {
        super.onQueryUserMinerListFail(e);
        ToastUtil.getInstance().shortLength(context, "" + e.getMessage());
    }

    @Override
    public void onMinerPayDepositSuccess(String resp) {
        super.onMinerPayDepositSuccess(resp);
        isUpActivityNeedRefresh = true;
        JSONObject param = new JSONObject();
        presenter.queryUserMinerList(param.toString());
    }

    @Override
    public void onMinerPayDepositFail(Exception e) {
        super.onMinerPayDepositFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage() + "");
    }

    @Override
    public void onMinerReturnDepositSuccess(String resp) {
        super.onMinerReturnDepositSuccess(resp);
        isUpActivityNeedRefresh = true;
        JSONObject param = new JSONObject();
        presenter.queryUserMinerList(param.toString());
    }

    @Override
    public void onMinerReturnDepositFail(Exception e) {
        super.onMinerReturnDepositFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage() + "");
    }

    @Override
    public void onBackPressed() {
        if (isUpActivityNeedRefresh) {
            setResult(RESULT_OK);
        }
        finish();
    }

    @OnClick({R.id.rl_miner_number})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_miner_number:
                startActivity(ComputeCodeEarningRecordActivity.createIntent(context));
                break;
        }
    }
}
